package com.amigo.online.consumer.video.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.amigo.online.common.base.controller.BaseConsumerController;
import com.amigo.online.common.core.response.Response;
import com.amigo.online.common.core.security.IgnoreSecurity;
import com.amigo.online.common.param.dto.video.LookVideoDto;
import com.amigo.online.common.param.dto.video.ShareVideoDto;
import com.amigo.online.common.param.dto.video.VideoCommentDto;
import com.amigo.online.common.param.dto.video.VideoDto;
import com.amigo.online.common.param.dto.video.VideoQueryDto;
import com.amigo.online.common.param.result.VideoInfo;
import com.amigo.online.common.util.UploadTempUtil;
import com.amigo.online.consumer.video.service.FileUploadService;
import com.amigo.online.consumer.video.service.UserService;
import com.amigo.online.consumer.video.service.VideoService;
import com.google.gson.Gson;

/**
 * 视频相关
 * @author amigo
 *
 */
@RestController
@RequestMapping(value = "/video", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class VideoController extends BaseConsumerController {
	
	@Autowired
	VideoService videoService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	FileUploadService fileUploadService;
	
	/**
	 * 
	 * @Title: uploadVideoFile   
	 * @Description: (上传图片)
	 * @param: @param files
	 * @param: @return      
	 * @return: ResponseEntity<Response> 
	 * @author: zxy  QQ:1363320658
	 * @date:   2019年1月14日 下午2:12:26   
	 * @version V1.0      
	 * @throws
	 */
	@PostMapping("/upload/img")
	public ResponseEntity<Response> uploadVideoFile(@RequestPart(value = "files") MultipartFile[] files) {
		// TODO: 2019/10/11 重构时需要注意
		long time = System.currentTimeMillis();
		List<String> resultList = fileUploadService.handleMultiFileUploadList(files);
		System.out.println(System.currentTimeMillis() - time);
		return success(resultList);
	}
	
	/**
	 * 
	 * @Title: uploadImgFile   
	 * @Description: (上传视频)
	 * @param: @param files
	 * @param: @return      
	 * @return: ResponseEntity<Response> 
	 * @author: zxy  QQ:1363320658
	 * @date:   2019年1月14日 下午2:12:58   
	 * @version V1.0      
	 * @throws
	 */
	@PostMapping("/upload/video")
	public ResponseEntity<Response> uploadImgFile(@RequestPart(value = "files") MultipartFile[] files) {
		List<String> resultList = fileUploadService.handleMultiFileUploadList(files);
		return success(resultList);
	}
	
	/**
	 * 
	 * @Title: newUserVideo   
	 * @Description: (用户新视频)
	 * @param: @param dto
	 * @param: @return      
	 * @return: ResponseEntity<Response> 
	 * @author: zxy  QQ:1363320658
	 * @date:   2019年1月14日 上午11:26:52   
	 * @version V1.0      
	 * @throws
	 */
	@PostMapping(value = "/new/v1")
	public ResponseEntity<Response> newUserVideo(VideoDto dto) {	
		return videoService.newUserVideo(dto);
	}
	
	//根据视频id获得视频信息
	@GetMapping(value = "/info/{id}")
	public ResponseEntity<Response> getVideoInfo(@PathVariable Long id) {
	     return videoService.getVideoInfoById(id);
	}
	
	//用户观看了一个视频
	@PostMapping(value = "/look")
	public ResponseEntity<Response> lookVideoById(HttpServletRequest request) {
		LookVideoDto dto = (LookVideoDto) getDto(request, LookVideoDto.class);
		return videoService.lookVideoById(dto);
	}
	//用户观看了一个视频(版本1)
	@PostMapping(value = "/look/{id}/{lookTime}")
	public ResponseEntity<Response> lookVideoById(@PathVariable Long id,@PathVariable Long lookTime) {
		return videoService.lookVideoById(id,lookTime);
	}
	/**
	 * 视频观看接口V3版本
	 * @param lookVideoDto
	 * @return
	 */
	@PostMapping(value = "/v3/look")
	public ResponseEntity<Response> lookVideoByIdV3(@RequestBody LookVideoDto lookVideoDto) {
        return videoService.lookVideoByIdV3(lookVideoDto);
	}
	
	//未登录状态用户观看了一个视频
	@PostMapping(value = "/lookNotLogined")
	public ResponseEntity<Response> lookNotLogined(HttpServletRequest request){
		LookVideoDto dto = (LookVideoDto) getDto(request, LookVideoDto.class);
		return videoService.lookNotLogined(dto);
	}
	
	//用户点赞了一个视频
	@PostMapping(value = "/up/{id}")
	public ResponseEntity<Response> upVideoById(@PathVariable Long id) {
		return videoService.upVideoById(id);
	}
	
	//获得用户对一个视屏的点赞状态
	@GetMapping(value = "/up/{id}")
	public ResponseEntity<Response> videoUpStatus(@PathVariable Long id) {
		return videoService.videoUpStatus(id);
	}
	
	//用户取消点赞一个视频
	@DeleteMapping(value = "/up/{id}")
	public ResponseEntity<Response> removeUpVideo(@PathVariable Long id) {
		return videoService.removeUpVideo(id);
	}
		
	//用户评论了一个视屏
	@PostMapping(value = "/comment/{id}")
	public ResponseEntity<Response> commentVideoById(@PathVariable Long id,HttpServletRequest request) {
		VideoCommentDto dto = (VideoCommentDto) getDto(request, VideoCommentDto.class);
		return videoService.commentVideoById(id,dto);
	}
	
	/*
	 * 新增一个视频
	 * 4种情况   
	 * 1、用户拍摄没选音乐   接受图片第一帧、视频流和视频内的音频流
	 * 2、用户拍摄选择了音乐    接受图片第一帧、视频流和音乐的fastdfs的地址
	 * 3、用户选择本地视频没选择音乐      接受图片第一帧、视频流
	 * 4、用户选择本地视频选择了音乐      接受图片第一帧、视频流和音乐的fastdfs地址
	 */
	@PostMapping(value = "/new")
	public ResponseEntity<Response> newUserVideo(
			@RequestPart(value = "files") MultipartFile[] files,
			VideoDto dto,
			@RequestHeader(value = "ACCESS_TOKEN",required = true) String token) throws ClientProtocolException, IOException {
		// TODO: 2019/10/11 重构时需要注意
		for (MultipartFile file : files) {
			String originalFilename = file.getOriginalFilename();
			System.out.println("originalFilename = " + originalFilename);
			if (originalFilename != null && file.getContentType().contains("video")) {
				String address = getAddress(UploadTempUtil.uploadResourceVideo(file, token));
				dto.setVideo(address);
				System.out.println("address = " + address);
			}else {
				System.out.println("originalFilename = " + originalFilename);
				String address = getAddress(UploadTempUtil.uploadResourceImg(file, token));
				dto.setCover(address);
				System.out.println("address = " + address);
			}
		}
		logger.info("上传结束");
		//userService.updateLocation(dto.getLongitude(), dto.getLatitude());		
		return videoService.newUserVideo(dto);
	}
	private String getAddress(String result) {
		String address = "";
		Response parseObject = new Gson().fromJson(result, Response.class);
		if (parseObject != null && parseObject.getData() != null) {
			Object data = parseObject.getData();
			if (data instanceof List) {
				List<String> addressList = (List<String>) data;
				address = addressList.get(0);
			}
		}
		return address;
	}
	//获得我的视频列表
	@GetMapping(value = "/my/videos/{page}/{size}")
	public ResponseEntity<Response> myVideos(@PathVariable Integer page,@PathVariable Integer size) {
        return videoService.myVideos(page,size);
	}
	
	//获得我看过的视频列表
	@GetMapping(value = "/my/looked/videos/{page}/{size}")
	public ResponseEntity<Response> myLokkerVideos(@PathVariable Integer page,@PathVariable Integer size) {
        return videoService.myLokkerVideos(page,size);
	} 
	
	//获得我上传的视频列表
	@GetMapping(value = "/my/uped/videos/{page}/{size}")
	public ResponseEntity<Response> myUpedVideos(@PathVariable Integer page,@PathVariable Integer size) {
        return videoService.myUpedVideos(page,size);
	}
	
	//根据id获得视频列表
	@GetMapping(value = "/user/videos/{uid}/{page}/{size}")
	public ResponseEntity<Response> getUserVideos(@PathVariable Long uid,@PathVariable Integer page,@PathVariable Integer size) {
        return videoService.getUserVideos(uid,page,size);
	}
	
	//根据id获得用户观看的视屏
	@GetMapping(value = "/user/looked/video/{uid}/{page}/{size}")
	public ResponseEntity<Response> userLookVideoList(@PathVariable Long uid,@PathVariable Integer page,@PathVariable Integer size) {
        return videoService.userLookVideoList(uid,page,size);
	}
	
	//根据id获得用户上传的视频
	@GetMapping(value = "/user/uped/list/{uid}/{page}/{size}")
	public ResponseEntity<Response> userUpVideoList(@PathVariable Long uid,@PathVariable Integer page,@PathVariable Integer size) {
        return videoService.userUpVideoList(uid,page,size);
	}	
	
	//获得推荐的视频列表
	@GetMapping(value = "/recommended/{deviceId}/{page}/{size}/{idNine}/{idTen}")
	public ResponseEntity<Response> recommendedVideoList(@PathVariable String deviceId,@PathVariable Integer page,@PathVariable Integer size,@PathVariable Long idNine,@PathVariable Long idTen) throws Exception {
        return videoService.recommendedVideoList(deviceId,page,size,idNine,idTen);
	}
	
	@GetMapping(value = "/recommended/v3/{deviceId}/{page}/{size}/{idNine}/{idTen}")
	public ResponseEntity<Response> recommendedVideoListv3(@PathVariable String deviceId,@PathVariable Integer page,
			@PathVariable Integer size,@PathVariable Long idNine,@PathVariable Long idTen) throws Exception {
		return videoService.recommendedVideoListv3(deviceId,page,size,idNine,idTen);
	}
	
	//获得附近的视频列表
	@GetMapping(value = "/near/{longitude}/{latitude}/{page}/{size}")
	public ResponseEntity<Response> nearVideoList(@PathVariable String longitude,@PathVariable String latitude,@PathVariable Integer page,@PathVariable Integer size) {
		userService.updateLocation(longitude,latitude);
		return videoService.nearVideoList(longitude,latitude,page,size);
	}
	
	//获得  谁看过我  用户列表
	@GetMapping(value = "/my/whoSawMe/{longitude}/{latitude}/{page}/{size}")
	public ResponseEntity<Response> whoSawMe(@PathVariable String longitude,@PathVariable String latitude,@PathVariable Integer page,@PathVariable Integer size) {
		return videoService.whoSawMe(longitude,latitude,page,size);
	}
	
	//获得我收藏的视频
	@GetMapping(value = "/my/collect/videos/{page}/{size}")
	public ResponseEntity<Response> myCollectVideos(@PathVariable Integer page,@PathVariable Integer size) {
        return videoService.myCollectVideos(page,size);
	}
	
	//用户收藏了一个视频
	@GetMapping(value="/collect/video/{videoid}")
	public ResponseEntity<Response> collectVideo(@PathVariable Long videoid){
		return videoService.collectVideo(videoid);
	}
	
	//用户取消收藏一个视频
	@GetMapping(value="/cancel/collect/{videoid}")
	public ResponseEntity<Response> cancelCollect(@PathVariable Long videoid){
		return videoService.cancelCollect(videoid);
	}
	
	//获得所有视频列表
	@GetMapping(value="/getAll")
	public ResponseEntity<Response> getAll(){
		return videoService.getAll();
	}
	
	//获得视频的评论列表
	@GetMapping(value = "/comments/{vid}/{page}/{size}")
	public ResponseEntity<Response> getCommentList(@PathVariable Long vid,@PathVariable Integer page,@PathVariable Integer size){
		return videoService.getCommentList(vid,page,size);
	}
	
	//获得关注者的视频列表
	@PostMapping(value = "/concern")
	public List<VideoInfo> getVideoInfoByUserIdList(HttpServletRequest request) {
		VideoQueryDto dto = (VideoQueryDto) getDto(request,VideoQueryDto.class);
		return videoService.getVideoInfoByUserIdList(dto);
	}
	
	//分享了一个视频
	@PostMapping(value = "/share")
	public ResponseEntity<Response> shareVideo(HttpServletRequest request) {
		ShareVideoDto dto = (ShareVideoDto) getDto(request, ShareVideoDto.class);
		return videoService.getDto(dto);	
	}

	//删除一个评论
	@GetMapping(value="/delete/video/comment/{id}/{vid}")
	public ResponseEntity<Response> deleteComment(@PathVariable Long id,@PathVariable Long vid){
		return videoService.deleteComment(id,vid);
	}
	
	/**
	 * 删除视频
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete/{id}")
	public ResponseEntity<Response> deleteVideoById(@PathVariable Long id) {
		return videoService.deleteVideoById(id);
	}
	
	/**
	 * 获取视频的评论数量
	 * @return
	 */
	@GetMapping(value = "/commentsCount/{vid}")
	@IgnoreSecurity
	public ResponseEntity<Response> getCommentoCount(@PathVariable Long vid){
		return videoService.getCommentsCount(vid);
	}
	
	/**
	 * 获取拍同款音乐基本信息
	 * add by kml 2018/10/18
	 * @return
	 */
	@GetMapping(value = "/sameMusicDetail/{musicId}")
	public ResponseEntity<Response> sameMusicDetail(@PathVariable Long musicId){
		return videoService.sameMusicDetail(musicId);
	}
	
	/**
	 * 获取拍同款音乐的视频
	 * add by kml 2018/10/18
	 * @return
	 */
	@GetMapping(value = "/getVideoInSameMusic/{musicId}/{page}/{size}")
	public ResponseEntity<Response> getVideoInSameMusic(@PathVariable Long musicId,
			@PathVariable Integer page,@PathVariable Integer size){
		return videoService.getVideoInSameMusic(musicId,page,size);
	}
public static void main(String[] args) {
	new Gson().fromJson("{\"meta\":{\"code\":200,\"success\":true,\"msg\":\"请求成功\"},\"data\":[\"2019/03/25/2026820190325235044577.png\"]}", Response.class);
}
}
